package com.bro.person.base.utils;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.http.HttpServletRequest;

/**
 * @author swallow
 * Created by swallow on 2018/9/7.<br>
 */
public class RequestUtil {

    private static final Logger logger = LoggerFactory.getLogger(RequestUtil.class);

    /**
     * 获取远程外网ip
     * @param request
     * @return
     */
    public static String getRemoteIP(HttpServletRequest request) {
        logger.trace("[RequestUtil][getRemoteIP]entering");
        String result = null;
        if (request.getHeader("x-forwarded-for") == null) {
            result = request.getRemoteAddr();
        }else{
            result = request.getHeader("x-forwarded-for");
        }

        //如果通过了多级反向代理的话，X-Forwarded-For的值并不止一个，而是一串IP值
        if(StringUtils.contains(result, ",")){

            String ip = result;
            //取 X-Forwarded-For中第一个非unknown的有效IP字符串。
            result = StringUtils.substring(result, 0, ip.indexOf(","));

            logger.warn("[RequestUtil][getRemoteIP]multiple ip, ip:{}, result:{}", ip, result);
        }
        logger.debug("[RequestUtil][getRemoteIP]result:{}", result);
        return result;
    }

    /**
     * 是否为post请求
     * @param request
     * @return
     */
    public static boolean isPost(HttpServletRequest request) {
        return StringUtils.equalsIgnoreCase("post", request.getMethod());
    }

    /**
     * 是否为get请求
     * @param request
     * @return
     */
    public static boolean isGet(HttpServletRequest request) {
        return StringUtils.equalsIgnoreCase("get", request.getMethod());
    }
}
